<template>
  <basic-container>
    <el-container> 
      <el-aside width="260px">
          <el-breadcrumb style="padding-bottom:20px;">
              <el-breadcrumb-item  style="background:#ffffff;position: absolute; z-index:100;top: 0px; left:6px;padding:10px 20px 5px 10px; box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);">
                <span style="font-weight:bold; ">当前项目：</span>
                {{projectInfo.projectName}}
              </el-breadcrumb-item>
          </el-breadcrumb>
          <avue-tree :option="treeOption" :data="treeData" @node-click="treeNodeClick">
          </avue-tree>
      </el-aside>
      <el-main>
        <avue-crud :option="option"
                  :table-loading="loading"
                  :data="data"
                  ref="crud"
                  v-model="form"
                  :defaults.sync="showColumn"
                  :permission="permissionList"
                  :before-open="beforeOpen"
                  @sortable-change="sortableChange"
                  @row-del="rowDel"
                  @row-update="rowUpdate"
                  @row-save="rowSave"
                  @refresh-change="refreshChange"
                  @search-change="searchChange"
                  @search-reset="searchReset"
                  @selection-change="selectionChange"
                  @current-change="currentChange"
                  @size-change="sizeChange"
                  @filter="filterChange"
                  @sort-change="sortChange"
                  @row-dblclick="handleRowDBLClick"               
                  >
          <template slot-scope="scope" slot="userIdForm">
            <div>
              <el-tag v-if="form.status != '1'" type="info">否</el-tag>
              <el-tag v-if="form.status == '1'" type="success">是</el-tag>
            </div>
          </template>
          <template slot-scope="scope" slot="userId">
            <div>
              <el-tag v-if="scope.row.status != '1'" type="info">否</el-tag>
              <el-tag v-if="scope.row.status == '1'" type="success">是</el-tag>
            </div>
          </template>
          <template slot-scope="scope" slot="menuLeft">
            <el-button type="primary"
                      size="small"
                      icon="el-icon-plus"
                      v-if="permission.general_project_s_batch_add"
                      @click.stop="openAddUserDialog">批量新增
            </el-button>
            <el-button type="primary"
                   size="small"
                   icon="el-icon-refresh-right"
                   v-if="permission.general_project_s_edit"
                   @click.stop="resetPassword">重置密码
            </el-button>
            <el-button type="danger"
                      size="small"
                      icon="el-icon-delete"
                      v-if="permission.general_project_s_batch_delete"
                      @click.stop="handleDelete">删 除
            </el-button>
          </template>
          <template slot-scope="scope" slot="menu">
            <el-button type="text"
                      size="small"
                      icon="el-icon-edit"
                      v-if="permission.general_project_s_edit  && scope.row.status !== '1'"
                      @click="createSysUser(scope.row)">创建用户
            </el-button>
            <el-button type="text"
                      size="small"
                      icon="el-icon-edit"
                      v-if="permission.general_project_s_edit  && scope.row.status == '1'"
                      @click="deleteSysUser(scope.row)">注销
            </el-button>
            <el-button type="text"
                      size="small"
                      icon="el-icon-user"
                      v-if="permission.general_project_s_edit && scope.row.status == '1'"
                      @click="openRoleDialog(scope.row)">角色
            </el-button>
          </template>
          <template slot="menuRight">
            <el-button type="default" v-if="permission.general_project_s_download" @click.stop="exportExcel"  title="下载" icon="el-icon-download" circle size="small"></el-button>
          </template>
        </avue-crud>
      </el-main>
    </el-container> 
    <!-- 
      批量添加用户对话框
     -->
    <el-dialog title="批量添加用户" :fullscreen='true' :close-on-click-modal='false' :visible.sync="addUserDialog">
      <general-staff-info-dialog 
        ref="childDialog"
        :hasSelectIds="oldUserListValue"
        @handleBatchAdd="handleBatchAdd"
        @getDialogStaffList="getDialogStaffList">
      </general-staff-info-dialog>
    </el-dialog>

    <!-- 
      添加角色对话框
     -->
    <el-dialog title="选择用户角色" width="60%"  :close-on-click-modal='false' @close="roleDialogClosed" :visible.sync="roleDialog">
        <div v-if="fullscreenLoading" style="width:100%; text-align:center;font-size:30px;top:100px;position:relative;z-index:5000">
          <i  class="el-icon-loading"></i>
        </div>
        <el-transfer v-model="roleValue" 
          filterable
          :titles="['可选角色', '已选角色']"
          :button-texts="['移除', '添加 ']"
          @change="roleChanged"
          :data="roleData">
        </el-transfer>
        <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" id="copyBtn" @click="handleAddUserRole($event)" >确定</el-button>
        <el-button size="small" @click="roleDialogClosed">取 消</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import {updateSysUserInfo,saveSysUserInfo,restAdminPassword,querySysUserInfo} from '@/api/system/sysUserInfoApi';
import {saveOrUpdateSysUserRoleRelationList} from '@/api/system/sysUserRoleRelationApi';
import {querySysRoleListPage,querySysRoleListByUserId} from '@/api/system/sysRoleApi';
import {exportGeneralOrgStaffRelationExcel,saveOrUpdateGeneralOrgStaffRelation,saveOrUpdateGeneralOrgStaffRelationList,saveGeneralOrgStaffRelation,saveGeneralOrgStaffRelationList,deleteGeneralOrgStaffRelation,queryGeneralOrgStaffRelation,queryGeneralOrgStaffRelationListPage,updateGeneralOrgStaffRelation,deleteGeneralOrgStaffRelationList} from '@/api/general/staff/generalOrgStaffRelationApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import GeneralStaffInfoDialog from '@/views/general/staff/generalStaffInfoDialog.vue'
export default {
  
  data() {
    return {
      //角色对话框
      fullscreenLoading: false,
      roleDialog: false,
      roleData: [],
      roleValue: [],
      oldRoleValue: [],
      roleChangeList:[],

      //添加用户对话框
      currentRow: {},

      importDataArea: '',
      addUserDialog: false,
      isFirstOpen: true,
      userListValue: [],
      oldUserListValue: [],
      staffList: [],

      form: {},
      selectionList: [],
      loading: false, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 120,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: true,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        cancelBtn: true,
        printBtn:false,
        editBtn:false,
        saveBtn: false,
        filterBtn:true,          
        menuWidth: 180,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:true,
        column: [
          
          {
            label: '用户名',
            prop: 'staffName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            width: 120,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '姓名',
            prop: 'realName', 
            type: 'input', 
            search: true,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            width: 150,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '机构名称',
            prop: 'belongOrgName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            width: 200,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '用户标识',
            prop: 'userId', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            slot: true,
            formslot: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          }
        ]
      },
      data: [],
      // 组织组织树形区
      checkedNode: '',
      currentOrg: {},
      orgType: '1',
      treeData:[],
      treeOption:{
        addBtn: false,
        menu: false,
        defaultExpandAll:false,
        props: {
          label: 'orgName',
          value: 'orgNo'
        },
      },
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  components: {
    GeneralStaffInfoDialog
  },
  computed: {
    ...mapGetters(['website','userInfo','projectOrgTree','permission','projectInfo']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.general_project_s_add, false),
        viewBtn: this.vaildData(this.permission.general_project_s_view, false),
        delBtn: this.vaildData(this.permission.general_project_s_delete, false),
        editBtn: this.vaildData(this.permission.general_project_s_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    /**
     * 注销用户-逻辑置为不可用
     */
    deleteSysUser(row){
      this.$confirm('确定注销用户?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.updateUserInfo(row,'0');
      }).catch(() => {});  
    },
    /**
     * 创建系统用户
     */
    createSysUser(row){
      this.$confirm('确定创建用户?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //创建记录
        if(row.userId == ''){
          this.addUserInfo(row);
        }
        //直接修改有效标志
        else{
          this.updateUserInfo(row,'1');
        }
      }).catch(() => {});  
      
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 添加用户记录
     */
    addUserInfo(row){
      this.reqParams.singleBody={
        userName:row.staffName,
        realName:row.realName,
        userType: 1,
        belongOrgNo: this.userInfo.belongOrgNo,
        belongOrgName: this.userInfo.belongOrgName,
        mobileNo: '888888888',
        validFlag: '1'
      };
      this.reqParams.singleBody.password = this.$toolUtil.encodeMd5(this.userInfo.tenantId);
      this.commonData = reqCommonMsg(this.reqParams)
      saveSysUserInfo(this.commonData).then(() => {
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
      });         
    },
    /**
     * 修改用户记录
     */
    updateUserInfo(row,validFlag){
      //先查询用户信息
      this.reqParams.singleBody.id = row.userId;
      let commonData = reqCommonMsg(this.reqParams)
      querySysUserInfo(commonData).then(res => {
        this.reqParams.singleBody = res.data.body.singleBody;
        this.reqParams.singleBody.validFlag = validFlag;
        this.commonData = reqCommonMsg(this.reqParams);
        // 修改记录
        updateSysUserInfo(this.commonData).then(() => {
          this.singleBody={}
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }, error => {
          //this.$console.log(error);
        });
      }); 
    },
    /**
     * 重置用户密码
     */
    resetPassword(){
      if (this.selectionList.length !== 1) {
        this.$message.warning('请选择一个租户数据');
        return;
      }
      else if (this.selectionList[0].status !== '1') {
        this.$message.warning('当前人员未注册用户！');
        return;
      }
      this.reqParams.singleBody = {
        id: this.selectionList[0].userId,
        password: this.$toolUtil.encodeMd5(this.userInfo.tenantId),
        tenantId: this.userInfo.tenantId
      }
      this.commonData = reqCommonMsg(this.reqParams)
      restAdminPassword(this.commonData).then(() => {
        this.singleBody={};
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '用户密码重置成功, 初始密码为：（'+this.userInfo.tenantId+'）!'
        });
      }, error => {
        //this.$console.log(error);
      });
    },
    /**
     * 打开角色对话框
     */
    async openRoleDialog(row){
      if(!row.userId){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '当前人员还未注册账号！！!'
        });
        return false;
      }
      this.currentRow = row;
      this.roleDialog = true;
      this.fullscreenLoading = true;
      this.singleBody.projectId = this.projectInfo.id;
      //获取所有角色列表
      this.reqParams =  {
        singleBody: this.singleBody,
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await querySysRoleListPage(this.commonData).then(res => {
        //this.$console.log('querySysRoleListPage = ',res)
        res.data.body.listBody.forEach(element => {
          this.roleData.push({
            key: element.id,
            label: '['+element.roleGroupName+']'+element.roleNickName,
            disabled: (element.status == '0') ? true: false
          });
        });
      }, error => {
        this.fullscreenLoading = false;
      });

      //获取当前用户的角色
      this.reqParams =  {
        singleBody: {
          userId: row.userId
        },
        currentPage: 1, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      await querySysRoleListByUserId(this.commonData).then(res => {
        //this.$console.log('querySysRoleListByUserId = ',res)
        res.data.body.listBody.forEach(element => {
          this.roleValue.push(element.id);
        });
        this.oldRoleValue = this.deepClone(this.roleValue)
        this.fullscreenLoading = false;
      }, error => {
        this.fullscreenLoading = false;
      });
    },
    /**
     * 角色对话框结束时回调
     */
    roleDialogClosed(done){
      this.roleDialog = false;
      this.roleData = [];
      this.roleValue = [];
    },
    /**
     * 穿梭框选择发生变化时
     */
    roleChanged(data,direct,changeValue){
    },
    /**
     * 保存角色
     */
    handleAddUserRole(){
      this.fullscreenLoading = true;
      // 前后角色对比，给新增和删除的打上标识
      let resultList = [];
      // 原列表不存在的表示新增的元素
      let inOldValue = false;
      let inNewValue = false;
      this.roleValue.forEach(element => {
        inOldValue = false;
        for(var i = 0 ; i < this.oldRoleValue.length; i++){
          if (element == this.oldRoleValue[i]) {
            inOldValue = true;
            i = this.oldRoleValue.size + 1;
          }
        }
        //若没找到表示新增元素
        if(!inOldValue){
          resultList.push({
            userId: this.currentRow.userId,
            roleId: element,
            validFlag: '1'
          })
        }
      });

      //新列表中不存在 表示 删除元素
      this.oldRoleValue.forEach(element => {
        inNewValue = false;
        for(var i = 0 ; i < this.roleValue.length; i++){
          if (element == this.roleValue[i]) {
            inNewValue = true;
            i = this.roleValue.size + 1;
          }
        }
        //若没找到表示删除元素
        if(!inNewValue){
          resultList.push({
            userId: this.currentRow.userId,
            roleId: element,
            validFlag: '0'
          })
        }
      });

      if(resultList.length > 0){
        this.reqParams =  {
          transCode: '0001',
          listBody: resultList
        }
        this.commonData = reqCommonMsg(this.reqParams)
        saveOrUpdateSysUserRoleRelationList(this.commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '保存成功!'
          });
          this.roleDialog = false;
          this.fullscreenLoading = false;
        }, error => {
          this.fullscreenLoading = false;
          //this.$console.log(error);
        });
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '角色未发生变化!'
        });
        this.fullscreenLoading = false;
      }
    },
    /**
     * 打开添加用户对话框
     */
    openAddUserDialog(){
      if(!this.$project.checkChooseProject()){
        return false;
      }
      if(this.currentOrg.orgNo){
        this.addUserDialog =  true;
        if(!this.isFirstOpen){
          this.$refs.childDialog.onLoad(this.$refs.childDialog);
        }
        else{
          this.isFirstOpen = false;
        }
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请先选择一个左边的组织架构再添加！！!'
        });
      }
    },
    /**
     * 获取添加用户弹窗查询出的用户列表信息
     */
    getDialogStaffList(staffList){
      this.staffList = staffList;
    },
    /**
     * 保存用户列表
     */
    handleBatchAdd(userListValue){
      this.fullscreenLoading = true;
      // 前后角色对比，给新增和删除的打上标识
      let resultList = [];
      // 原列表不存在的表示新增的元素
      let inOldValue = false;
      let inNewValue = false;
      // 判断是否有新增数据
      userListValue.forEach(element => {
        inOldValue = false;
        for(var i = 0 ; i < this.oldUserListValue.length; i++){
          if (element.id == this.oldUserListValue[i]) {
            inOldValue = true;
            i = this.oldUserListValue.size + 1;
          }
        }
        //若没找到表示新增元素
        if(!inOldValue){
          resultList.push({
            belongOrgNo: this.currentOrg.orgNo,
            belongOrgName: this.currentOrg.orgName,
            staffId: element.id,
            staffName: element.staffId,
            realName: element.staffName,
            validFlag: '1'
          })
        }
      });

      // 判断是否有删除数据
      this.oldUserListValue.forEach(id => {
        inNewValue = false;
        for(var i = 0 ; i < userListValue.length; i++){
          if (id == userListValue[i].id) {
            inNewValue = true;
            i = userListValue.size + 1;
          }
        }
        //若没找到表示删除元素
        if(!inNewValue){
          for(var i = 0 ; i < this.staffList.length; i++){
            if(id == this.staffList[i].id){
              resultList.push({
                belongOrgNo: this.currentOrg.orgNo,
                belongOrgName: this.currentOrg.orgName,
                staffId: this.staffList[i].id,
                staffName: this.staffList[i].staffId,
                realName: this.staffList[i].staffName,
                validFlag: '0'
              })
              i = this.staffList.length + 1;
            }
          }
        }
      });
      if(resultList.length > 0){
        this.reqParams =  {
          transCode: '0001',
          listBody: resultList
        }
        this.commonData = reqCommonMsg(this.reqParams)
        saveOrUpdateGeneralOrgStaffRelationList(this.commonData).then(() => {
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '添加成功!'
          });
          this.onLoad(this.page);
          userListValue = null;
          this.addUserDialog = false;
          this.fullscreenLoading = false;
        }, error => {
          //this.$console.log(error);
        });
      }
      else{
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '用户未发生变化!'
        });
        this.fullscreenLoading = false;
      }
    },
    /**
     * 组织树形菜单点击时触发事件
     */
    treeNodeClick(data){
      this.currentOrg = data
      this.onLoad(this.page)
    },
    /**
     * 加载列表数据
     */
    onLoad(page) {
      if(!this.$project.checkChooseProject()){
        return false;
      }
      if(this.currentOrg.orgNo){
        this.singleBody.belongOrgNo=this.currentOrg.orgNo;
      }
      else {
        this.singleBody.belongOrgNo = this.projectInfo.id;
      }
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: this.website.maxPageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      queryGeneralOrgStaffRelationListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
        this.oldUserListValue = [];
        this.data.forEach(element => {
          this.oldUserListValue.push(element.staffId)
        });
        this.selectionClear();
      }, error => {
        this.loading = false; 
      });
    },
    /**
     * 新增一条记录
     */
    rowSave(row, done, loading) {
      if(!this.$project.checkChooseProject()){
        return false;
      }
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      saveGeneralOrgStaffRelation(this.commonData).then(() => {
        done();
        this.singleBody={};
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });         
      //this.$console.log("row = ",row ,loading)
    },
    /**
     * 修改一条记录
     */
    rowUpdate(row, index, done, loading) { 
      this.reqParams.singleBody = row;
      this.commonData = reqCommonMsg(this.reqParams)
      updateGeneralOrgStaffRelation(this.commonData).then(() => {
        done();
        this.singleBody={}
        this.onLoad(this.page);
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '操作成功!'
        });
      }, error => {
        //this.$console.log(error);
        loading();
      });
      //this.$console.log('loading = ',loading)
    },
    /**
     * 删除一条记录
     */
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.singleBody = row;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralOrgStaffRelation(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }).catch(() => {});
    },
    /**
     * 双击打开详细窗口
     */
    handleRowDBLClick (row, event) {
      this.$refs.crud.rowView(row,row.$index);
    },
    /**
     * 批量新增记录
     */
    openBatchAddDialog(){
      this.batchAddDialog = true;
    },
    // 
    handleImport() {
      if(!this.$project.checkChooseProject()){
        return false;
      }
      this.loading=true;
      var dataList = new Array();
      if(this.importDataArea){
        var lineList = this.importDataArea.split('\n')
        lineList.forEach((element,index) => {
          if(element.trim() != ''){
            var field = element.split('\t')
            var fieldList = {
              belongOrgNo:field[0],
              belongOrgName:field[1],
              staffId:field[2],
              staffName:field[3],
              realName:field[4],
            }
            dataList[index] = fieldList
            //this.$console.log('fieldList = ',fieldList)
          }
        });
        //批量写入记录
        this.reqParams.listBody = dataList;
        this.commonData = reqCommonMsg(this.reqParams)
        saveGeneralOrgStaffRelationList(this.commonData).then(() => {
          this.loading=false;
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
        }, error => {
          //this.$console.log(error);
          this.loading=false;
          loading();
        });      
        //this.$console.log('lineList=',dataList)
      }
      else{
        this.loading=false;
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '数据格式不正确!'
        });
      }
    },
    /**
     * 搜索重置
     */
    searchReset() {
      this.conditions =[];
      this.singleBody = {};
      this.onLoad(this.page);
    },
    /**
     * 搜索
     */
    searchChange(params, done) {
      this.singleBody = params
      this.page.currentPage = 1;
      this.onLoad(this.page);
      done();
    },
    refreshChange(){
      this.getProjectOrgTree();
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**
     * 处理批量删除
     */
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.reqParams.listBody = this.ids;
          this.commonData = reqCommonMsg(this.reqParams);
          return deleteGeneralOrgStaffRelationList(this.commonData);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        }).catch(() => {});
    },
    /**
     * 拷贝记录
     */
    handleCopy(row){
      this.$confirm('确定复制数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading=true;
        let copyValue=row;
        copyValue.id='0';
        copyValue.dataSign='0'
        copyValue.tableName='拷贝 '+ copyValue.tableName; 
        this.reqParams.singleBody = copyValue;
        this.commonData = reqCommonMsg(this.reqParams)
        saveSysToolTables(this.commonData).then(() => {
          this.singleBody={};
          this.onLoad(this.page);
          this.$message({
            customClass:'zZindex',
            type: 'success',
            message: '操作成功!'
          });
          this.loading=false;
        }, error => {
          //this.$console.log(error);
          this.loading=false;
        });
      }).catch(() => {});       
    },
    /**
     * 打开编辑、查询弹窗前查询记录
     */  
    beforeOpen(done, type) {
      
      if (['edit', 'view'].includes(type)) {
        
      }
      done();
    },
    /**
     * 翻页查询
     */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /**
     * 更改每页条数
     */
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    /**
     * 自定义查询条件
     */
    filterChange(result) {
      this.page.currentPage = 1;
      this.conditions = filterFormat(result)
      this.onLoad(this.page);
    },
    /**
     * 列表排序
     */
    sortChange(val){
      this.orderRules=val
      this.onLoad(this.page);
    },
  
    /**
     * 导出Excel
     */
    exportExcel() {
      if(!this.$project.checkChooseProject()){
        return false;
      }
      if(!this.currentOrg.orgNo){
        this.$message({
          customClass:'zZindex',
          type: 'warning',
          message: '请先选择左侧的机构再下载!'
        });
        return false;
      }
      let condition = [
        {column: 'belongOrgNo', type: '=', value: this.currentOrg.orgNo}
      ]
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: condition,
        orderRule: this.orderRules,
        currentPage:1, 
        pageSize: 100
      }
      this.reqParams.singleBody.belongProjectNo = this.projectInfo.id;
      this.commonData = reqCommonMsg(this.reqParams)
      exportGeneralOrgStaffRelationExcel(this.commonData);
    },
    /**
     * 获取组织树
     */
    getProjectOrgTree(){
      if(!this.$project.checkChooseProject()){
        return false;
      }
      let getOrgTimer = setInterval(() => {
        if(this.projectOrgTree){
          this.treeData = [];
          this.treeData =  this.projectOrgTree;
          clearInterval(getOrgTimer);
        }
      }, 100);
    }
  },
  created() {
    if(!this.projectInfo || !this.projectInfo.projectName){
      this.$message({
        type: 'warning',
        message: '请选择一个项目再进入！'
      });
      this.$router.push({path: '/general/project/generalMyProjectSelector'});
    }
    this.showColumn = this.$getStore({name:  this.userInfo.userId +'generalOrgStaffRelationColumn'});
    this.getProjectOrgTree();
  },
  watch: {
    showColumn: {
      handler(newValue, oldValue) {
        this.$setStore({name:  this.userInfo.userId+'generalOrgStaffRelationColumn', content: this.showColumn});
      },
      deep: true
      //this.$setStore({name: this.userInfo.userId +'generalOrgStaffRelationColumn', content: this.showColumn});
    }
  }
};
</script>
<style>
.el-main {
    margin-left: 5px !important;  
    border-left: 10px solid #f3f3f3 !important;  
}
</style>